<?
require_once(dirname(__FILE__).'/../models/Users.php');
require_once(dirname(__FILE__).'/../models/UsersRequests.php');
require_once(dirname(__FILE__).'/../models/Categories.php');
require_once(dirname(__FILE__).'/../models/Pages.php');
require_once(dirname(__FILE__).'/../models/Offers.php');

class IndexController extends Main_Controller_Action {
	public function preDispatch()
    {
        //Database::instance()->getConn()->debug =1;
        $filter = "";
		$orderBy = "ORDER BY id DESC";
		$limit = 30;
		$this->view->buyerRequests = ModelMapper::instance('UsersRequests')->findFilteredPaged($filter, $orderBy, $limit, 0);
    }

	function indexAction() {
		//Database::instance()->getConn()->debug =1;
		$currentPage = intval($this->getRequest()->getParam('pageNo'));
		if ($currentPage == 0)
			$currentPage = 1;

		
		
		
		if ($this->getRequest()->getParam('query')){
			$this->view->queryString = $this->getRequest()->getParam('query');
			$prefix = '/search/page/';
		}
		else {
			$prefix = '/filter/page/';
			$this->view->queryString = false;
		}
		if ($this->_request->getParam('filter') != '')
			$suffix = '/' . $this->_request->getParam('filter') . '/' . $this->_request->getParam('query');
		else
			$suffix = '/recent/' . $this->_request->getParam('query');
		
		if ($this->getRequest()->getParam('filter'))	{
			switch ($this->getRequest()->getParam('filter')){
				case 'popularity':{
					$orderBy = "ORDER BY popularity DESC";
					break;
				}
				case 'rating':{
					$orderBy = "ORDER BY rating DESC";
					break;
				}
				default:{
					$orderBy = "ORDER BY id DESC";
					break;
				}
			}
		} else {
			$orderBy = "ORDER BY id DESC";
		}
		
		if ($this->getRequest()->getParam('query')){
			$filter = "
				WHERE title REGEXP '".$this->getRequest()->getParam('query')."' 
				OR tags REGEXP '".$this->getRequest()->getParam('query')."'
				OR description REGEXP '".$this->getRequest()->getParam('query')."'";
		} else {
			$filter = "";
		}
				
		//$filter = "";
		//$orderBy = "ORDER BY id DESC";

		$sessionLimit = new Zend_Session_Namespace('limit');
		$sessionOffset = new Zend_Session_Namespace('offset');

		$limit = $this->config->records->limitPerPage;
		$rCount = ModelMapper::instance('Offers')->getCount($filter);
		
		$this->view->pager = DataUtils::pager($currentPage, $rCount, $limit, $sessionLimit, $sessionOffset, $prefix, $suffix, 6);
		$offset = $sessionOffset->offset;
			
		$offers = ModelMapper::instance('Offers')->findFilteredPaged($filter, $orderBy, $limit, $offset);
		
		$this->view->offers = $offers;
		$this->view->rCount = $rCount;
		$this->view->limit = $limit;
		$this->view->offset = $offset;
		$this->view->filter = $this->getRequest()->getParam('filter');
		
		$this->view->selectedCategory = false;
		
		if ($this->getRequest()->getParam('query')){
			$this->view->filterRecentUrl = '/search/page/1/recent/'.$this->getRequest()->getParam('query');
		} else {
			$this->view->filterRecentUrl = '/filter/page/1/recent';
		}
		
		if ($this->getRequest()->getParam('query')){
			$this->view->filterPopularityUrl = '/search/page/1/popularity/'.$this->getRequest()->getParam('query');
		} else {
			$this->view->filterPopularityUrl = '/filter/page/1/popularity';
		}
		
		if ($this->getRequest()->getParam('query')){
			$this->view->filterRatingUrl = '/search/page/1/rating/'.$this->getRequest()->getParam('query');
		} else {
			$this->view->filterRatingUrl = '/filter/page/1/rating';
		}
	}

	function categoryAction() {
		//Database::instance()->getConn()->debug =1;
		$currentPage = intval($this->getRequest()->getParam('pageNo'));
		if ($currentPage == 0)
			$currentPage = 1;

		
		
		
		$prefix = '/category/page/';
		
		if ($this->_request->getParam('filter') != '')
			$suffix = '/' . $this->_request->getParam('filter') . '/' . $this->_request->getParam('categoryId'). '/' . $this->_request->getParam('categoryId');
		else
			$suffix = '/recent/' . $this->_request->getParam('categoryId'). '/' . $this->_request->getParam('categoryId');
		
		if ($this->getRequest()->getParam('filter'))	{
			switch ($this->getRequest()->getParam('filter')){
				case 'popularity':{
					$orderBy = "ORDER BY popularity DESC";
					break;
				}
				case 'rating':{
					$orderBy = "ORDER BY rating DESC";
					break;
				}
				default:{
					$orderBy = "ORDER BY id DESC";
					break;
				}
			}
		} else {
			$orderBy = "ORDER BY id DESC";
		}
		
		if ($this->getRequest()->getParam('query')){
			$filter = "WHERE title REGEXP '".$this->getRequest()->getParam('query')."' OR tags REGEXP '".$this->getRequest()->getParam('query')."'";
		} else {
			$filter = "";
		}
				
		$filter = "WHERE categories_id = ".$this->getRequest()->getParam('categoryId');
		
		$sessionLimit = new Zend_Session_Namespace('limit');
		$sessionOffset = new Zend_Session_Namespace('offset');

		$limit = $this->config->records->limitPerPage;
		$rCount = ModelMapper::instance('Offers')->getCount($filter);
		
		$this->view->pager = DataUtils::pager($currentPage, $rCount, $limit, $sessionLimit, $sessionOffset, $prefix, $suffix, 6);
		$offset = $sessionOffset->offset;
			
		$offers = ModelMapper::instance('Offers')->findFilteredPaged($filter, $orderBy, $limit, $offset);
		
		$this->view->offers = $offers;
		$this->view->rCount = $rCount;
		$this->view->limit = $limit;
		$this->view->offset = $offset;
		$this->view->filter = $this->getRequest()->getParam('filter');
		$this->view->queryString = $this->getRequest()->getParam('query');
		$this->view->category = ModelMapper::instance('Categories')->find($this->getRequest()->getParam('categoryId'));
		$this->view->selectedCategory = $this->getRequest()->getParam('categoryId');
		$this->view->filterRecentUrl = '/category/page/'.$currentPage.'/recent/'.$this->view->category->getId().'/'.$this->view->category->getCategory();
		$this->view->filterPopularityUrl = '/category/page/'.$currentPage.'/popularity/'.$this->view->category->getId().'/'.$this->view->category->getCategory();
		$this->view->filterRatingUrl = '/category/page/'.$currentPage.'/rating/'.$this->view->category->getId().'/'.$this->view->category->getCategory();
	}
	
	function pageAction() {
		$auth = Zend_Auth::getInstance();
		if ($auth->hasIdentity()) {
			$userDetails = $auth->getIdentity();
			$this->view->userDetails = $userDetails;
		}

		$page = ModelMapper::instance('Pages')->find($this->getRequest()->getParam('pageId'));
		if (is_null($page)) {
			$this->_helper->redirector('', '');
		}

		$this->view->page = $page;
	}
	
	function offerAction() {
		//Database::instance()->getConn()->debug=1;
		$offer = ModelMapper::instance('Offers')->find($this->getRequest()->getParam('offersId'));
		if (is_null($offer)) {
			$this->_helper->redirector('', '');
		}

		$this->view->offer = $offer;
		$filter = "WHERE users_id =".$offer->getUsersId();
		$orderBy = "";
		$limit = 10;
		$offset = 0;
		$otherOffers = ModelMapper::instance('Offers')->findFilteredPaged($filter, $orderBy, $limit, $offset);
		
		
		$tags = $offer->getTags();
		if ($tags != '')
			$tagsArray = explode(',', $tags);
		else {
			$tagsSplitted = 'offer';
			$tagsArray = array();
		}
		foreach ($tagsArray as &$v){
			$v = trim($v);
		}
		$tagsSplitted = implode('|', $tagsArray);
		
		$filter = "WHERE tags REGEXP '".$tagsSplitted."'";
		$orderBy = "";
		$limit = 10;
		$offset = 0;
		$relatedOffers = ModelMapper::instance('Offers')->findFilteredPaged($filter, $orderBy, $limit, $offset);

		
		$smarty = $this->view->getEngine();

		$this->view->otherOffers = $otherOffers;
		$this->view->relatedOffers = $relatedOffers;
		$this->view->selectedCategory = $offer->getCategory()->getId();
		$this->view->userInfo = true;
	}

	function registerAction() {
		// Creating a Zend_View instance
		$view = new Zend_View();

		// Originating request:
		$captcha = new Zend_Captcha_Image(array(
			'wordLen' => 4,
			'timeout' => 50,
			'imgDir' => $_SERVER['DOCUMENT_ROOT'] . '/cache/captcha',
			'ImgUrl' => '/cache/captcha',
			'width' => 180,
			'height' => 60,
			'font' => 'public/fonts/arial.ttf',
			'fontSize' => 30
		));

		$this->view->captchaId = $captcha->generate();
		$this->view->captcha = $captcha->render($view);
		$this->view->formData = false;
		$this->view->message = false;
		//$smarty = $this->view->getEngine();
		//$tpl = $smarty->fetch('index/register.tpl');

		//$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		//$this->getResponse()->sendResponse();
		//exit();
	}

	function validateUsernameAction() {
		$username = $_GET['addForm']['username'];

		$isValid = ModelMapper::instance('Users')->checkIsValidUsername($username);
		echo json_encode($isValid);

		exit();
	}

	function registerSaveAction() {

		$formData = $this->_request->getParam('addForm');
		$captchaSess = new Zend_Session_Namespace('Zend_Form_Captcha_' . $_POST['captchaId']);
		
		if ($captchaSess->saved != true){
			if (trim($formData['captchaText']) != trim($captchaSess->word) || trim($captchaSess->word) == '') {
				$badCaptcha = true;
		
				// Creating a Zend_View instance
				$view = new Zend_View();
	
				// Originating request:
				$captcha = new Zend_Captcha_Image(array(
					'wordLen' => 4,
					'timeout' => 50,
					'imgDir' => $_SERVER['DOCUMENT_ROOT'] . '/cache/captcha',
					'ImgUrl' => '/cache/captcha',
					'width' => 180,
					'height' => 60,
					'font' => 'public/fonts/arial.ttf',
					'fontSize' => 30
				));
	
				$this->view->captchaId = $captcha->generate();
				$this->view->captcha = $captcha->render($view);
				$this->view->formData = $formData;
				$this->view->message = ' bad phrase, fill once again';
	
				$smarty = $this->view->getEngine();
				$tpl = $smarty->fetch('index/register.tpl');
			} else {
				//Database::instance()->getConn()->debug=1;
				//debug($formData);
				
				$obj = new Users();
				$obj->setAppsId($this->view->appsId);
				$obj->setUsername(trim(strip_tags(stripcslashes($formData['username']))));
				//$obj->setFirstName(trim(strip_tags(stripcslashes($formData['firstName']))));
				$obj->setFirstName('');
				//$obj->setLastName(trim(strip_tags(stripcslashes($formData['lastName']))));
				$obj->setLastName('');
				$obj->setPassword(md5(trim($formData['password'])));
				$obj->setRegistrationDate(date('Y-m-d H:i:s'));
				$obj->setEmail(trim(strip_tags(stripcslashes($formData['email']))));
				$obj->setStatusesId(intval($this->config->statuses->general->active));
				$obj->setIsAdministrator(0);
				$obj->setIsOperator(0);
				//debug($obj);
	
				$this->view->password = $formData['password'];
				$this->view->user = $obj;
				
				$smarty = $this->view->getEngine();
				//$tpl = $smarty->fetch('ajax/registered.tpl');
				$tpl = $smarty->fetch('index/registered.tpl');
				$captchaSess->saved = true;
	
			}
			$this->view->tplContent = $tpl;
		}else {
			header('Location: /login');
			exit;
		}
		
		//$this->getResponse()->setHeader('Content-Type', 'text/html')->appendBody($tpl);
		//$this->getResponse()->sendResponse();
		//exit();
	}

	function userAction(){
		$username = $this->getRequest()->getParam('username');
		$filter = "WHERE username = '".$username."'";
		$user = ModelMapper::instance('Users')->findOneFiltered($filter);
		
		//debug($user);
		$this->view->user = $user;
	}
	/**
     * Locale change
     */
	function langAction() {
		$lang = new Zend_Session_Namespace('lang');

		if ($this->getRequest()->has('langId')) {
			if (!is_dir($_SERVER['DOCUMENT_ROOT'] . $this->config->locale->localeDir . '/' . $this->getRequest()->getParam('langId'))) {
				$lang->lang = $this->config->locale->defaultLocale;
			} else {
				$lang->lang = $this->getRequest()->getParam('langId');
			}
		}
		$this->_helper->redirector('', '');
		exit;
	}
}
?>
